//
//  CImageGridCell.m
//  ImageGridCell
//
//  Created by 为为 on 14-7-1.
//  Copyright (c) 2014年 为为. All rights reserved.
//

#import "CImageGridCell.h"

#define LEFT_MARGIN 20
#define RIGHT_MARGIN 20
#define TOP_MARGIN 4
#define BOTTOM_MARGIN 20 

#define NUM_IMAGE_PER_ROW 4
#define LABEL_HEIGHT 30
#define IMAGE_HEIGHT 60
#define IMAGE_WIDTH IMAGE_HEIGHT
#define IMAGE_V_MARGIN 20
#define IMAGE_MARGIN_TO_LABEL 10

#define DOWNLOAD_BUTTON_TAG 220
#define DOWNLOAD_BUTTON_WIDTH 120
#define DOWNLOAD_BUTTON_HEIGHT 40

#define DELETE_BUTTON_CENTER_X 10
#define DELETE_BUTTON_CENTER_Y 10
#define DELETE_BUTTON_WIDTH 26
#define DELETE_BUTTON_HEIGHT 26
#define DELETE_BUTTON_TAG 101
#define DELETE_BUTTON_IMAGE @"btn_delete.png"


@interface CImageGridCell ()
@property (nonatomic, strong) UILabel* titleLabel;
@property (nonatomic, strong) NSMutableArray* imageButtonArray;
@property (nonatomic, assign) bool deleting;
@end

@implementation CImageGridCell


- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
		// Initialization code
		self.imageArray = [NSMutableArray array];
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        [self initTitleLabel];
		[self initDelete];
    }
    return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)prepareForReuse
{
}

- (void)initTitleLabel
{
    if (self.titleLabel) {
        [self.titleLabel removeFromSuperview];
    }
    
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.frame = CGRectMake(0, TOP_MARGIN, self.bounds.size.width, LABEL_HEIGHT);
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.backgroundColor = [UIColor colorWithWhite:0.7 alpha:0.2];
    [self.contentView addSubview:self.titleLabel];
}

- (void)initDelete
{
	self.deletable = false;
	self.deleting = false;
	UITapGestureRecognizer* tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backgroundTapped:)];
	[self.contentView addGestureRecognizer:tapGestureRecognizer];
}

- (void)backgroundTapped:(UIGestureRecognizer*)recognizer
{
	[self stopDelete];
}

- (CGFloat)recalcHeightWithImageCount:(int)count
{
	CGFloat height = 0;
	height += LABEL_HEIGHT;
	
	height += TOP_MARGIN;
	
	if (count) {
		height += BOTTOM_MARGIN;
	}
	
	int numOfRow = (int)count/NUM_IMAGE_PER_ROW;
	if (count%NUM_IMAGE_PER_ROW) {
		numOfRow += 1;
	}
	height += numOfRow*IMAGE_HEIGHT;
	if (numOfRow > 1) {
		height += (numOfRow-1)*IMAGE_V_MARGIN;
	}
	
	return height;
}

- (void)resetImageButtons
{
    int imageButtonStartIndex = self.imageButtonArray?self.imageButtonArray.count:0;
    int newImageButtonCount = (int)self.imageArray.count - (int)self.imageButtonArray.count;
    for (int i=0; i<-newImageButtonCount; i++) {
        [self.imageButtonArray removeLastObject];
    }
    //wei todo
	if (self.imageButtonArray) {
		for (UIButton* button in self.imageButtonArray) {
			[button removeFromSuperview];
		}
	}
	
	CGFloat colDelta = (self.bounds.size.width-(LEFT_MARGIN+RIGHT_MARGIN)-IMAGE_WIDTH)/(NUM_IMAGE_PER_ROW-1);
	CGFloat rowDelta = IMAGE_HEIGHT+IMAGE_V_MARGIN;
	CGFloat colBase = LEFT_MARGIN;
	CGFloat rowBase = TOP_MARGIN+LABEL_HEIGHT+IMAGE_MARGIN_TO_LABEL;
	int i=0;
	NSMutableArray* buttonArray = [NSMutableArray array];
	for (UIImage* image in self.imageArray) {
		UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
		int row = i/NUM_IMAGE_PER_ROW;
		int col = i%NUM_IMAGE_PER_ROW;
		CGRect frame = CGRectMake(colBase+col*colDelta, rowBase+row*rowDelta, IMAGE_WIDTH, IMAGE_HEIGHT);
		button.frame = frame;
		button.clipsToBounds = NO;
        [button setImage:image forState:UIControlStateNormal];
		[button addTarget:self action:@selector(imageButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        if (self.deletable) {
            UILongPressGestureRecognizer* gustureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(imageLongPressed:)];
            [button addGestureRecognizer:gustureRecognizer];
			UIButton* deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
			[deleteButton addTarget:self action:@selector(deleteButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
			[deleteButton setImage:[UIImage imageNamed:DELETE_BUTTON_IMAGE] forState:UIControlStateNormal];
			deleteButton.tag = DELETE_BUTTON_TAG;
			deleteButton.frame = CGRectMake(0, 0, DELETE_BUTTON_WIDTH, DELETE_BUTTON_HEIGHT);
			deleteButton.center = CGPointMake(DELETE_BUTTON_CENTER_X, DELETE_BUTTON_CENTER_Y);
			deleteButton.hidden = true;
			[button addSubview:deleteButton];
        }
		[self.contentView addSubview:button];
		[buttonArray addObject:button];
        i++;
        button.userInteractionEnabled = true;
	}
    CGRect frame = self.frame;
    frame.size.height = [self recalcHeightWithImageCount:self.imageArray.count];
    self.frame = frame;
    
	self.imageButtonArray = buttonArray;
    
    if (self.deleting) {
        [self startDeleteAnimation];
    }
}

- (void)setImageArray:(NSArray *)imageArray
{
	_imageArray = imageArray;
    [self resetImageButtons];
}

- (NSString *)title
{
	return self.titleLabel.text;
}

- (void)setTitle:(NSString *)title
{
	self.titleLabel.text = title;
}

- (void)setNewImage:(UIImage *)image forIndex:(int)index
{
    if (!image || index<0 || index>=self.imageArray.count) {
        return;
    }
    
    UIButton* button = [self.imageButtonArray objectAtIndex:index];
    if (button) {
        [button setImage:image forState:UIControlStateNormal];
    }
}

- (void)imageButtonPressed:(id)sender
{
	if (self.deleting) {
		[self stopDelete];
	} else {
		if (self.imagePressedBlock) {
            NSUInteger index = [self.imageButtonArray indexOfObject:sender];
			UIImage* image = [(UIButton*)sender imageForState:UIControlStateNormal];
			self.imagePressedBlock(self, image, index);
		}
	}
//    NSLog(@"image pressed");
}

- (void)downloadButtonPressed:(id)sender
{
    if (self.downloadPressedBlock) {
        self.downloadPressedBlock(self);
    }
//    NSLog(@"download");
}

- (void)deleteButtonPressed:(id)sender
{
	UIButton *button = (UIButton*)((UIButton*)sender).superview;
	[button removeFromSuperview];
	int index = NSNotFound;
	for (int i=0; i<self.imageButtonArray.count; i++) {
		if (button == [self.imageButtonArray objectAtIndex:i]) {
			index = i;
			break;
		}
	}
	if (index != (int)NSNotFound) {
		for (int i=(int)self.imageButtonArray.count-1; i>index; i--) {
			UIButton* curButton = [self.imageButtonArray objectAtIndex:i];
			UIButton* preButton = [self.imageButtonArray objectAtIndex:i-1];
			[UIView animateWithDuration:0.2
							 animations:^{
								 curButton.center = preButton.center;
							 }];
		}
        UIImage* image = [self.imageArray objectAtIndex:index];
        if (self.imageDeletedBlock) {
            self.imageDeletedBlock(self, image, index);
        }
		if ([self.imageButtonArray isKindOfClass:[NSMutableArray class]]) {
			NSMutableArray* mutableArray = (NSMutableArray*)self.imageButtonArray;
			[mutableArray removeObject:button];
		}
		if ([self.imageArray isKindOfClass:[NSMutableArray class]]) {
			NSMutableArray* mutaleArray = (NSMutableArray*)self.imageArray;
			[mutaleArray removeObjectAtIndex:index];
		}
	}
//	NSLog(@"delete button");
}

- (void)setDeletable:(BOOL)deletable
{
    BOOL oldDeletable = _deletable;
    _deletable = deletable;
    if (oldDeletable != deletable) {
        [self resetImageButtons];
    }
}

- (void)imageLongPressed:(UILongPressGestureRecognizer*)longPressRecognizer
{
    if (self.deleting) {
        return;
    }
    
	if (longPressRecognizer.state ==  UIGestureRecognizerStateBegan) {
		[self startDelete];
	}
}

- (void)startDelete
{
    if (!self.deleting) {
        self.deleting = true;
        [self startDeleteAnimation];
    }
}

- (void)stopDelete
{
    if (self.deleting) {
        self.deleting = false;
        [self stopDeleteAnimation];
    }
}

- (void)startDeleteAnimation
{
	for (UIButton* button in self.imageButtonArray) {
		UIView* deleteButton = [button viewWithTag:DELETE_BUTTON_TAG];
		deleteButton.hidden = false;
		
        srand([[NSDate date] timeIntervalSince1970]);
        float rand=(float)random();
        CFTimeInterval t=rand*0.0000000001;
        [UIView animateWithDuration:0.1
							  delay:t
							options:0
						 animations:^{
							 button.transform=CGAffineTransformMakeRotation(-0.05);
						 }
						 completion:^(BOOL finished){
							 [UIView animateWithDuration:0.1
												   delay:0
												 options:UIViewAnimationOptionRepeat|UIViewAnimationOptionAutoreverse|UIViewAnimationOptionAllowUserInteraction
											  animations:^{
													 button.transform=CGAffineTransformMakeRotation(0.05);
												 }
											  completion:nil];
						 }];
	}
}

- (void)stopDeleteAnimation
{
	for (UIButton* button in self.imageButtonArray) {
		UIView* deleteButton = [button viewWithTag:DELETE_BUTTON_TAG];
		deleteButton.hidden = true;
		
		[UIView animateWithDuration:0.1
							  delay:0.0
							options:UIViewAnimationOptionAllowUserInteraction|UIViewAnimationOptionBeginFromCurrentState
						 animations:^{
							 button.transform = CGAffineTransformIdentity;
						 }
						 completion:^(BOOL finished) {
							 
						 }];
	}
}

- (int)heightFromImageCount:(int)count
{
	int height = 0;
	height = [self recalcHeightWithImageCount:count];
	return height;
}

@end
